<?php

namespace App\V3\V3_2_7\Controllers;

use App\Helper\DBRSAUtil;
use App\Http\Controllers\Controller;
use App\Services\CommonService;
use App\V3\Api\Models\AnnounceModel;
use App\V3\V3_2_7\Models\CustomerServiceModel;
use App\V3\V3_2_7\Models\SystemConfigModel;
use App\V3\V3_2_7\Services\AdminService;
use App\V3\V3_2_7\Services\MessBoardService;
use App\V3\V3_2_7\Services\StorageService;
use App\V3\V3_2_7\Services\UserMenuService;
use Illuminate\Http\Request;

class DefaultIndexController extends Controller
{
    //
    public function index(Request $request)
    {
        $info = [];
        $token = $request->header('token');
        $info['announce'] = AnnounceModel::query()
            ->where([
                'delete_flag' => 0,
                'is_publish' => 1
            ])->first();
        if (!empty($token)) {
            $tokenInfo = self::checkToken($token);
            if (!empty($tokenInfo['code']))
                return fail('', $tokenInfo['msg']);

            $info['user_center'] = AdminService::userCenter(
                $tokenInfo['userId'],
                $tokenInfo['mainUserId'],
                $tokenInfo['userType']
            );
            $data = [
                'main_id' => $tokenInfo['mainUserId'],
                'user_id' => $tokenInfo['userId'],
                'user_type' => $tokenInfo['userType']
            ];
            $info['user_menu_list'] = UserMenuService::info($data);
            $info['shelf_location_list'] = StorageService::storageShelfLocation(['main_id' => $data['main_id']]);
            $result = [];
            if (!$tokenInfo['userType']) {
                $result = AdminService::mainGetModelInfo($tokenInfo['mainUserId']);
            } else {
                $result = AdminService::userGetModelInfo($tokenInfo['userId']);
            }
            $info['login_permissions'] = $result;
            return success($info);
        }
    }

    static private function checkToken($token)
    {
        if (empty($token)) {
            return [
                'code' => 2,
                'msg' => 'token验证失败',
                'data' => '',
            ];
        }

        $array = explode(' ', $token);
        //私钥获取
        $private = SystemConfigModel::getConfigValue('private');

        if (count($array) < 2) {
            return [
                'code' => 2,
                'msg' => 'token验证失败',
                'data' => '',
            ];
        }

        //解密加密参数并验证
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        $rsadata = json_decode($rsadata, true);

        if ($rsadata['userId'] != $array['0']) {
            return [
                'code' => 2,
                'msg' => 'token验证失败',
                'data' => '',
            ];
        }

        return $rsadata;
    }
}
